package roborescue;

import jason.RoborescueEnv;
import jason.asSyntax.Structure;

import java.rmi.RemoteException;

import robocode.rescue.RobotInfo;
import Model.RoboFuzzyModel;

public class TimeYTeamEnv extends RoborescueEnv {
	
	 private RoboFuzzyModel model;  
	 
	 	private final int numRobos = 5;
	    private RobotInfo[] robos;
	    private RobotInfo[] inimigos;  
	    
	    //Para inicializacoes necessarias
	    @Override
	    public void setup() {
	    	robos = new RobotInfo[numRobos];
	        inimigos = new RobotInfo[numRobos];
	        	        
	        model = new RoboFuzzyModel(getTeamRef());
	        try {
	        	
	        	robos = getServerRef().getMyTeamInfo(myTeam);
		        inimigos = getServerRef().getEnemyTeamInfo(myTeam);
		        
		        model.setRobos(robos); 
	 	        model.setInimigos(inimigos);
	 	        double meuCampo = getServerRef().getEnemyTeamInfo(myTeam)[0].getX();
	 	        double campoInimigo = getServerRef().getMyTeamInfo(myTeam)[0].getX();
	        	model.setCampo(meuCampo, campoInimigo);
	        	
	        } catch (RemoteException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	        
	    }

	    @Override
	    public boolean executeAction(String ag, Structure action) {

	        try {
	            mainLoop();
	            Thread.sleep(20);
	        } catch (RemoteException ex) {
	            ex.printStackTrace();
	        } catch (InterruptedException ex) {
	            ex.printStackTrace();
	        }

	        return true;

	    }
	    
	    public void mainLoop() throws RemoteException {
	        
	    	robos = getServerRef().getMyTeamInfo(myTeam);
	        inimigos = getServerRef().getEnemyTeamInfo(myTeam);
	        
	        model.updateTeamRef(getTeamRef());
	        model.updateRobos(robos); 
	        model.updateInimigos(inimigos);
	        model.atualizaVariaveis();
	        model.executeFuzzy();
	        model.setStrategy();
	        model.executeActions();
	        
	    }
	    @Override
	    public void end() {
	        try {
	          super.getEnvironmentInfraTier().getRuntimeServices().stopMAS();
	        } catch (Exception ex) {
	          ex.printStackTrace();
	          System.exit(1);
	        }
	    }
	    
	    public static void main(String[] args) {
	        TimeYTeamEnv team = new TimeYTeamEnv();
	        team.init(new String[]{"TimeY", "localhost"});
	        team.setup();
	        while(true) {
	          try {
	            team.mainLoop();
	            Thread.sleep(20);
	          } catch (RemoteException ex) {
	            ex.printStackTrace();
	          } catch (InterruptedException ex) {
	            ex.printStackTrace();
	          }
	        }
	    }
}
